<script setup>
// import { Decimal } from 'decimal.js'
import { showToast } from "vant";
import { ref, reactive, onBeforeMount, onMounted } from "vue";
import { countryList } from "@/data/countryList";
import {
  upDateUserInfo,
  upLoadUserImage,
  selectUserInfoByUid,
} from "@/server/api/profile";
import { insertRegisterData } from "@/server/api/userInfo";
import { getCountryList } from "@/server/api/BuyerData";
import { useRouter } from "vue-router";

const router = useRouter();

import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";

import { ToastFun } from "@/hook/toast";
import { userStore } from "@/stores/userStore";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const user = useUseStore();
const useStore = useIndexStore();
let userId = useUseStore().userId; // 用户id
// 属性数组
const data = reactive([
  // {
  //   attribute: "gender",
  //   id: 2,
  //   value: "",
  // },
  // {
  //   attribute: "age",
  //   id: 3,
  //   value: "",
  // },
  {
    attribute: "me.profile.email",
    id: 4,
    value: "",
  },
  {
    attribute: "me.profile.country",
    id: 5,
    value: "",
  },
  // {
  //   attribute: "language",
  //   id: 6,
  //   value: "",
  // },
]);

const userDatInfo = ref(null)
const showCountry = ref(false)
const showPicker = ref(false)
let subData = {};
const currentID = ref(null);

// 当前所编辑的表单索引
const currentFormId = ref(null);
// 打开表单
const openForm = (id) => {
  currentID.value = id;
  currentFormId.value = id;
};

// 获取用户初始数据函数
const getUserInfo = async () => {
  const res = await selectUserInfoByUid(user.userId);
  console.log(userStore().userInfo);
  useStore.submitData = res.data.data;
  useUseStore().userInfo = res.data.data;
};

// 提交表单
const submit = async () => {
  useStore.submitData.uid = user.userId;
  useStore.submitData.userName = "";
  const data = await upDateUserInfo(useStore.submitData);
  console.log("userInfo22:", data);
  if (data.data.code == 200) {
    useStore.isRequird = true;
    ToastFun("success")
  }
};

//关闭表单编辑
const closeForm = () => {
  currentFormId.value = null;
  submit();
  console.log("subData:", subData);
};

// 表单校验函数
function validateEmail(email) {
  const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return emailRegex.test(email);
}

const closeEmailForm = () => {
  const isValidEmail = validateEmail(useStore.submitData.email);
  if (isValidEmail) {
    // 提交更新后的数据
    currentFormId.value = null;
    submit();
  } else {
    showToast(t("me.profile.email"));
  }
};

const closeEmail = () => {
  const isValidEmail = validateEmail(useStore.submitData.email);
  if (!useStore.submitData.email || isValidEmail) {
    currentFormId.value = null;
    submit();
  } else {
    showToast(t("me.profile.eamil"));
  }
};
// 接收子组件传过来的数据
const acceptVal = (value, field, index) => {
  // 更新store中的数据
  useStore.submitData[field] = value;
  // 直接更新响应式数据
  data[index].value = value;
  // 提交数据后立即更新
  setTimeout(() => {
    submit();
  }, 200);
};



// 用户所在国家数据
// const countryData = ref();
const countryData = countryList.filter(item => item.countryName !== "piftware");
// 接收country/lanuage组件传过来的数据
const countryMsg = (value, field, index) => {
  // 更新国家数据
  useStore.submitData[field] = value.countryCode;
  useStore[field] = index;

  // 设置延迟更新，确保数据传递到store
  setTimeout(() => {
    submit();
    currentFormId.value = null;
  }, 200);
};

const fileList = ref("");
const afterRead = async (file) => {
  var formData = new FormData();
  formData.append("file", file.file);
  console.log("file:", file.file);
  fileList.value = file.objectUrl;
  useStore.imgUrl = file.objectUrl;

  // 轻提示
  ToastFun("Loading", {
    duration: 0,
    msg: t("me.profile.upload"),
    forbidClick: true,
  });


  // 上传头像接口
  const data = await upLoadUserImage({ data: formData, userId });
  console.log("上传头像：", data);
  if (data.data.code === 200) {
    useStore.isRequird = true;
    getUserInfo();
    ToastFun("show", {
      msg: t("me.profile.success"),
    });
  } else {
    ToastFun("", {});
  }
};

// 获取国家列表数据
const getCountryListFun = async () => {
  let { data } = await getCountryList();

  countryData.value = data.data;
  //console.log(countryData.value);
};

// 匹配密码正则
const regex = /^[a-zA-Z0-9_]{6,15}$/;
// 用户设置pi密码接口的请求体
let formList = reactive({
  piName: useUseStore().userInfo.piName,
  uid: useUseStore().userId,
  password: "",
});

// 用户添加账号密码方法
const addPasswordFun = async () => {
  // 判断密码是否符合正则
  if (!regex.test(formList.password)) {
    ToastFun("show", { msg: "Password error", position: "bottom" }); // 轻提示
    formList.password = "";
    return;
  }

  ToastFun("Loading", { duration: 1000 }); // 加载提示
  let { data } = await insertRegisterData(formList);
  data.code == 200 ? ToastFun("success", {}) : ToastFun("", {});
};
console.log(userStore().userInfo);
const findEmail = () => {
  if (useUseStore().userInfo.email !== "" && useUseStore().userInfo.email !== null) {
    // 更新本地数据
    data[0].value = useUseStore().userInfo.email;
    useStore.submitData.email = useUseStore().userInfo.email; // 保证store的数据是最新的
  }
}
const findCountry = () => {
  if (user.userInfo.country !== null && user.userInfo.country !== "") {
    const country = countryData.find(item => item.countryCode === user.userInfo.country);
    if (country) {
      data[1].value = "/images/countryImg/" + country.img;
      useStore.submitData.country = user.userInfo.country; // 确保store中的数据更新
    }
  }
};
console.log(user.userInfo.userImage, "12313");


// //选择国家
// const changeItemAddFun = (countryCode, img) => {
//   console.log(countryCode, img, "12313");
//   useStore.submitData.country = countryCode
//   useStore.submitData.img
//   showPicker.value = false
// }

//提交
const onSubmit = async () => {
  ToastFun("Loading", { duration: 1000 }); // 加载提示
  const data = {
    uid: useStore.submitData.uid,
    userName: useStore.submitData.userName,
    email: useStore.submitData.email,
    country: useStore.submitData.country
  }
  const res = await upDateUserInfo(data);
  if (res.data.code === 200) {
    ToastFun("success", {})
    useUseStore().userInfo.email = useStore.submitData.email
    router.push({ path: "MeView" });

  } else {
    ToastFun("", {});
  }

}

//选中
const passCountryCode = (value) => {
  console.log("Selected country code:", value);
  useStore.submitData.country = value
}

onBeforeMount(() => {
  getUserInfo();
  getCountryListFun();
  findEmail();
  findCountry();
  console.log(useStore.submitData.userImage, "i");
});
</script>

<template>
  <header class="header">
    <PageTop />
    <div class="title">{{ $t("me.profile.title") }}</div>
  </header>

  <div class="avater">
    <img :src="`${useStore.submitData.userImage}` || '/images/pipayshop_logo.png'" alt="" class="avater-img" />
    <img src="/images/Me/edite_avater.png" alt="" class="edite-Icon" />
    <!-- 上传头像 -->
    <van-uploader :after-read="afterRead" image-fit="cover" class="album" />
  </div>

  <!-- <div class="item" v-for="(item, index) in data" :key="index">
    <div class="container-my">
      <div class="attribute">{{ $t(item.attribute) }}&nbsp;&nbsp;{{ item.value }}</div>
      <div class="attribute" v-if="item.id == 4"><span style="font-size: 18px;">{{ $t(item.attribute)
      }}</span>&nbsp;&nbsp;{{ item.value }}</div>
      <div v-else-if="item.id == 5" style="display: flex;width: 100vw;">
        <span style="font-size: 18px;"> {{ $t(item.attribute) }}</span>
        <div style="margin-left: auto;"><img style="vertical-align: top;" :src="item.value"></div>
      </div>
      <div @click="openForm(item.id)" class="right-bar">
        <span class="name" v-if="useStore.submitData[item.attribute] == 0 ||
          useStore.submitData[item.attribute] == 1
          ">
          {{ genderVal }}
        </span>
        <span class="name">
          {{ useStore.submitData[item.attribute] }}
        </span>
        <img src="/images/Me/rightArrow@2x.png" alt="" :class="['arrow', useIndexStore().isRtl ? 'trun_180' : '']" />
      </div>
    </div>

    <div class="underline"></div>
  </div> -->


  <!-- 
  <MaskOver v-if="4 == currentFormId" @click.self="closeEmail">
    <InputName field="email" setName="email" index="0" @updata="acceptVal">
      <span class="confirm" @click="closeEmailForm">{{ $t("me.profile.confirm") }}</span>
    </InputName>
  </MaskOver>

  <MaskOver v-if="5 == currentFormId" @click.self="closeForm">
    <CountryForm field="country" :currentIndex="useStore.country" @acceptCountry="countryMsg" :countryData="countryData">
    </CountryForm>
  </MaskOver> -->


  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <!-- <van-field v-model="useStore.submitData.userName" name="用户名" label="用户名" placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" /> -->
      <van-field v-model="useStore.submitData.email" type="email" name="邮箱" label="邮箱" placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]" />



      <!-- <van-field v-model="useStore.submitData.country" is-link readonly name="picker" label="国家" placeholder="点击选择国家"
        @click="showPicker = true" :suffix-icon="`/images/countryImg/${useStore.submitData.img}`" :suffix-text="''"
        class="country-field" />
      <van-popup v-model:show="showPicker" :style="{ maxHeight: '80vh', height: 'auto' }" position="bottom" scrollable>
        <div class="popup-container">
          <div class="content" v-for="(item, i) in countryData" :key="i" v-if="useStore.submitData !== null">
            <div :class="['item', countryCon == item.countryCode ? 'con' : '']" class="item-content"
              @click="changeItemAddFun(item.countryCode, item.img)">
              <span class="country-name">{{ item.countryName }}</span>
              <img v-lazy="`/images/countryImg/${item.img}`" alt="" class="country-img" />
            </div>
          </div>
        </div>
      </van-popup> -->


      <van-field is-link readonly name="country" label="国家" placeholder="国家" class="text-end"
        v-model="useStore.submitData.country" @click="showCountry = true"
        :rules="[{ required: true, message: $t('ReceivingCountry') }]" />

      <!-- 国家弹窗 -->
      <van-popup v-model:show="showCountry" round class="pop" position="bottom"
        :style="{ height: '50%', backgroundColor: '#F5F5F5FF' }">
        <ul class="countrySelect">
          <van-radio-group v-model="useStore.submitData.country" @change="passCountryCode">
            <li v-for="item in countryData" :key="item.countryCode" class="country-item">
              <van-radio :name="item.countryCode" :label="item.countryCode">
                <div class="content">
                  <div class="country">{{ item.countryEName }}</div>
                  <img :src="`/images/countryImg/${item.img}`" class="country-img" />
                </div>
              </van-radio>
            </li>

          </van-radio-group>
        </ul>
      </van-popup>



    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>




  <div class="password">
    <div class="title">{{ $t("me.profile.outside") }}</div>

    <div class="input">
      <input type="" v-model="formList.password" />
      <div class="btn" @click="addPasswordFun">
        {{ $t("me.profile.submit") }}
      </div>
    </div>

    <div class="tips">{{ $t("me.profile.tips") }}</div>
  </div>
</template>

<style lang="scss" scoped>
.header {
  .title {
    position: absolute;
    left: 50%;
    top: 12rem;
    transform: translateX(-50%);
    text-align: center;
    font-size: 20rem;
    font-weight: 500;
  }
}

.confirm {
  position: absolute;
  top: -2rem;
  right: 30rem;
  color: #642e8e;
}

.avater {
  position: relative;
  margin: 30rem auto;
  width: 88rem;
  height: 88rem;
  border-radius: 50%;
  overflow: hidden;
  // background-color: bisque;

  .avater-img {
    width: 100%;
    object-fit: cover;
  }

  .edite-Icon {
    position: absolute;
    top: 12rem;
    right: 10rem;
    width: 24rem;
    height: 24rem;
    z-index: 10;
  }

  :deep(.album) {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    opacity: 0;
  }
}

.item {
  .container-my {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 16rem;
    margin-bottom: 17rem;

    .attribute {
      // flex: 8;
      font-size: 16rem;
      font-weight: 500;
    }

    .right-bar {
      .name {
        // flex: 3;
        font-size: 20rem;
        font-weight: 400;
        margin-right: 10rem;
      }

      .arrow {
        // flex: 1;
        width: 24rem;
        height: 24rem;
        line-height: 24rem;
        vertical-align: bottom;
      }
    }
  }

  .underline {
    margin: 0 auto;
    width: 358rem;
    height: 1rem;
    margin-bottom: 17rem;
    border-bottom: 1rem solid #e5e5e5;
  }
}

:deep(.data-picker) {
  position: absolute;
  bottom: 0;
  width: 100vw;
}

.submit {
  width: 80rem;
  border: 1rem solid #e5e5e5;
  text-align: center;
  margin: 0 auto;
  font-size: 24rem;
}

.password {
  padding: 30rem 16rem 0;

  >.title {
    width: 100%;

    text-align: center;
    font-size: 18rem;
    font-weight: 500;

    padding: 0 0 10rem;
  }

  >.input {
    display: flex;
    font-size: 14rem;

    >input {
      border: 0;
      border-bottom: 1rem solid #eee;

      flex: 1;
    }

    >.btn {
      color: #fff;
      background: #662d91;
      border-radius: 5rem;

      padding: 10rem 15rem;
      margin: 0 10rem;
    }
  }

  >.tips {
    width: 100%;
    margin-top: 10rem;

    text-align: center;
    font-size: 12rem;
    color: rgb(165, 165, 165);
  }
}

.popup-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  /* iOS平滑滚动 */
}

.content {
  overflow-y: auto;
  max-height: 100%;
}

.item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.item-content:hover {
  background-color: #f5f5f5;
}

.item.con {
  background-color: #e0f7fa;
  /* Highlight selected item */
}

.country-name {
  font-size: 16px;
  color: #333;
  flex: 1;
  padding-left: 10px;
}

.country-img {
  width: 30px;
  /* Fixed width for consistency */
  height: 30px;
  /* Fixed height for consistency */
  border-radius: 50%;
  object-fit: cover;
  /* Ensure the image doesn't stretch/distort */
}

.pop {
  .countrySelect {
    width: 390rem;
    height: 500rem;


    li {
      padding: 10rem;
      display: flex;
      bottom: 1px solid;
      justify-content: space-between;

      .country {
        font-size: 16rem;
        font-weight: bold;
      }

      img {
        width: 30rem;
        height: 30rem;
      }
    }
  }

  .country-item .content {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 左右两端对齐 */
  width: 100%; /* 确保占满整个可用空间 */
}

.country-item .country {
  flex: 1; /* 占据左边的剩余空间 */
}

.country-item .country-img {
  width: 24px; /* 根据需要调整图片大小 */
  height: 24px;
  object-fit: cover; /* 保证图片不会变形 */
  margin-left: 10px; /* 图片与文字之间的间距 */
}

  // .regionSelect {
  //   width: 390rem;
  //   height: 500rem;

  //   li {
  //     padding: 10rem;
  //     display: flex;
  //     bottom: 1px solid;
  //     justify-content: space-between;

  //     .region {
  //       font-size: 16rem;
  //       font-weight: bold;
  //     }
  //   }
  // }
}
</style>
